<template>
  <div class="body">
    <van-nav-bar title="流程详情" left-arrow @click-left="onClickLeft" />
    <div class="title">
      <div class="groupsDetail-letf">
        <div>{{ procFormDatas.title }}</div>
        <div>表单编码：{{ procFormDatas.formInstId }}</div>
        <div>发起时间：{{ procFormDatas.initiationTime }}</div>
      </div>
    </div>
    <div class="forms">
      <Engine
        :mode="MODE.MOBILE"
        :scene="SCENE.PREVIEW"
        :dataInject="dataInject"
        :nodeInject="nodeInject"
        :bridge="bridge"
        @submit="onSubmit"
        ref="engine"
      >
      </Engine>
    </div>
    <div style="clear: both"></div>

    <div>
      <div class="flow">流程</div>
      <van-steps direction="vertical" :active="approvedNodeNum - 1" active-icon="success" active-color="#1989fa">
        <van-step v-for="(item, index) in steps" :key="index">
          <template>
            <div class="stepPage">
              <div class="stepTitle">
                <h3>{{ item.nodeName }}</h3>
              </div>
              <template>
                <div v-if="item.nodeStauts == 'running'">
                  {{ item.operatorList.length }}人{{ getActivateType(item) }}
                  <span>{{ item.nodeStautsDesc === '' ? '' : '(' + item.nodeStautsDesc + ')' }}</span>
                </div>
                <template v-if="item.operatorList && item.operatorList.length <= 2">
                  <span v-for="(items, i) in item.operatorList" :key="i">
                    <div v-if="item.nodeStauts == 'running'">
                      {{ items.realName || items.realname }}
                    </div>
                    <div v-else>
                      <div>
                        {{ items.realName || items.realname }}
                        <span>{{
                            item.nodeStautsDesc === '' ? '' : '(' + item.nodeStautsDesc + ')'
                          }}</span>
                      </div>
                    </div>
                    <div>{{ items.opinion || '' }}</div>
                  </span>
                </template>
                <template v-if="item.operatorList && item.operatorList.length > 2">
                  <div class="showMorePeople">
                    <div v-for="respons in sliceArray(0, 2, item.operatorList)" :key="respons.index">
                      <div>
                        {{ respons.realName || respons.realname }}
                      </div>
                    </div>
                    <div class="all-header">
                      <van-image @click="showUserMore(item.operatorList)" width="30" height="30" :src="allIcon">
                      </van-image>
                    </div>
                  </div>
                </template>
                <div>{{ item.remark || '' }}</div>
              </template>
            </div>
          </template>
        </van-step>
      </van-steps>
    </div>
    <div style="text-align: center; height: 50px" v-if="actBtn || actRevokeButton">
      <van-goods-action style="border-top: 1px solid #f7f4f4;" >
        <van-goods-action-icon
          v-if="actRevokeButton && actBtn"
          icon="revoke"
          text="撤销"
          @click="showRevocation = true"
        />
        <van-goods-action-icon
          v-if="!actBtn && actRevokeButton"
          style="width：100%"
          icon="revoke"
          text="撤销"
          @click="showRevocation = true"
        />
        <van-goods-action-icon icon="ellipsis" v-if="actBtn" text="更多" @click="showMore = true" />
        <div v-if="actBtn" style="width: 60px"></div>
        <van-goods-action-button v-if="actBtn" type="warnings" text="拒绝" @click="reject" />
        <van-goods-action-button v-if="actBtn" color="#0b9df7" @click="agree" type="danger" text="同意" />
      </van-goods-action>
    </div>
    <!-- 查看更多人 -->
    <van-dialog v-model="selectedShowUserMore" title="标题" show-cancel-button>
      <div v-for="(items, index) in selectedUser" :key="index" style="padding-left: 29px">
        <div>
          <div>
            {{ items.realName || items.realname }}
            <span>{{ items.nodeStautsDesc === '' ? '' : '(' + items.nodeStautsDesc + ')' }}</span>
          </div>
        </div>
        <div>{{ items.opinion || '' }}</div>
        <!-- <br /> -->
      </div>
    </van-dialog>
    <!-- 操作列表 -->
    <van-action-sheet v-model="showMore" key="con" cancel-text="取消">
      <div class="confirmList">
        <p v-if="actBtn" @click="onContact('z')">转交</p>
        <p v-if="actBtn" @click="onContact('j')">加签</p>
        <p v-if="actBtn" @click="onGoBack()">退回</p>
      </div>
    </van-action-sheet>
    <!-- 退回 -->
    <van-action-sheet v-model="dialogGoBack" key="back" cancel-text="取消">

      <div class="confirmList" v-if="approvalsNodeList.length > 0">
        <p v-for="(item, index) in approvalsNodeList" @click="goBack(item)" :key="index">
          {{ getNodeName(item, index) }}
        </p>
      </div>
      <div v-else class="confirmList">
        <p>暂无数据</p>
      </div>
    </van-action-sheet>
    <!-- 撤回 -->
    <van-dialog v-model="showRevocation" @confirm="revoke" confirmButtonColor="#1E8DF5" show-cancel-button>
      <div class="confirmList">
        <p>确定要撤回申请吗？</p>
      </div>
    </van-dialog>
    <!-- 转交加签 -->
    <ContactPicker
      :type="1"
      :key="time"
      ref="mychild"
      :visible="visibleContactPicker"
      :approvedby="approvedby"
      :value="value"
      :max="max"
      @confirm="confirm"
      @closePicker="closePicker"
    />
  </div>
</template>
<script>
import {
  Engine,
  MODE,
  SCENE,
  Bridge,
  injectRequest,
  provideRequest,
  NodeStore,
  convert,
} from '@/components/oa/oa-process.umd'
const bridge = new Bridge()
import { post, get, put } from '@/api/request'
import {
  getUserListNotdel,
  queryFormData,
  queryProcessResult,
  saveProcessStart,
  getSelectListByIds,
  addUpload,
  getRefuse,
  getAgree,
  getRevoke,
  getPassOn,
  getAddAssignee,
  getGoBack,
} from '@/api/api'
import '@/components/oa/oa-process.css'
import ContactPicker from '@/components/choiceuse/ContactPicker'
import { Dialog } from 'vant'
// import { getAction, deleteAction, putAction, putparamsAction,postAction, httpAction } from '@/api/manage'
import store from '@/store'

export default {
  data() {
    return {
      MODE,
      SCENE,
      nodeInject: new NodeStore(),
      bridge,
      dataInject: {
        getCanvas: () => {
          return this.procFormInfoqueryByIds()
        },
      },
      title: this.$route.query.fullName,
      steps: [],
      onSubmitLoading: false,
      defaultType: ['START', 'target_originator', 'target_approval', 'target_role', 'target_management'],
      allIcon: require('@/assets/img/icon_quanbu.png'),
      addIcon: require('@/assets/img/btn_tianjia.png'),
      visibleContactPicker: false, //组件是否展示
      time: new Date().getSeconds(), //去缓存
      approvedby: [],
      value: '',
      max: 1, //是否可以选择多个
      nodeSort: '',
      allUserList: [],
      actRevokeButton: this.$route.query.revokeShowFlag !== 'false' && this.$route.query.processResult === 'running',
      actBtn: this.$route.query.my || false, //操作按钮
      showMoreList: false, //同意拒绝是否展示
      moreInfo: [],
      procFormDatas: {},
      showMore: false,
      dialogGoBack: false,
      showRevocation: false, //撤销
      approvedNodeNum: 1, //进度条
      approvalsNodeList: [], //退回列表
      selectedUser: [], //查看更多人的列表
      selectedShowUserMore: false,
    }
  },
  created() {
    this.browserRedirect()
    injectRequest({ post, get, put })
    window.test = this
  },
  mounted() {
    //监听节点变化
    this.procFormInfoqueryByIds()
    var that = this
    bridge.addEventListener('nodes', (nodes) => {
      that.showFlow = false
      that.processDataVo = []
    })

    // console.log(that.$refs.engine, 'that.$refs.engine')
  },
  components: {
    Engine,
    ContactPicker,
  },
  methods: {
    browserRedirect() {
      var sUserAgent = navigator.userAgent.toLowerCase()
      if (/ipad|iphone|midp|rv:1.2.3.4|ucweb|android|windows ce|windows mobile/.test(sUserAgent)) {
        //跳转移动端页面
        console.log('跳转移动端页面')
        // this.$router.push('/mobileapplyFormDetails')
        // this.$router.push({
        //   path: '/mobileapplyFormDetails',
        //   query: { processInstanceId: this.$route.query.processInstanceId, title: this.$route.query.title },
        // })

        //
      } else {
        //跳转pc端页面
        // this.$router.push('/applyFormDetails')
        this.$router.push({
          path: '/applyFormDetails',
          query: {
            processInstanceId: this.$route.query.processInstanceId,
            taskId: this.$route.query.taskId,
            revokeShowFlag: this.$route.query.initiator === store.getters.userInfo.username,
            processResult: this.$route.query.processResult,
            title: this.$route.query.title,
            my: this.$route.query.my,
          },
        })

        console.log('跳转pc端页面')
      }
    },

    onClickLeft() {
      // this.$router.push('/process/approval/MyTaskNeedToExcute')
      this.$router.go(-2)
    },
    onGoBack() {
      this.dialogGoBack = true
      this.showMore = false
    },
    onContact(v) {
      this.showMore = false
      this.visibleContactPicker = true
      this.confirmType = v
    },
    // 退回
    goBack(v) {
      // console.log(v.nodeId,'v.nodeId')
      // if(v.nodeId === ''){
      //   return  this.$message.error('退回节点必填')
      // }
      let par = {
        taskId: this.$route.query.taskId,
        targetNodeId: v.nodeId,
      }
      getGoBack(par).then((res) => {
        this.dialogGoBack = false
        if (String(res.code) === '500') {
          this.$message.error('操作失败')
        } else {
          this.$message.success('操作成功')
          setTimeout(() => {
            this.$router.push({ path: '/process/approval/MyTaskNeedToExcute', query: {} })
          }, 100)
        }
      })
    },
    closePicker() {
      this.visibleContactPicker = false
      this.value = ''
    },
    confirm(value) {
      if(value){
      let par = {
        taskId: this.$route.query.taskId,
        userKey: value,
      }
      let url = this.confirmType == 'j' ? getAddAssignee : getPassOn
      url(par).then((res) => {
        if (String(res.code) === '500') {
          this.$message.error('操作失败')
        } else {
          this.$message.success('操作成功')
          setTimeout(() => {
            this.$router.push({ path: '/process/approval/MyTaskNeedToExcute', query: {} })
          }, 100)
        }
      })
      }
      this.visibleContactPicker = false
      this.value = ''
    },

    revoke() {
      let par = {
        processInstanceId: this.$route.query.processInstanceId,
      }
      getRevoke(par).then((res) => {
        this.dialogrevoke = false
        if (String(res.code) === '500') {
          this.$message.error('操作失败')
        } else {
          this.$message.success('操作成功')
          setTimeout(() => {
            this.$router.push({ path: '/process/approval/MyTaskNeedToExcute', query: {} })
          }, 100)
        }
      })
    },
    getActivateType(item) {
      if (item.properties.actionerRules[0].type === 'target_originator') {
        return ''
      }
      if (item.properties.activateType) {
        if (item.properties.activateType === 'ONE_BY_ONE') {
          return '依次审批'
        } else if (item.properties.agreeAll) {
          return '会签'
        } else {
          return '或签'
        }
      }
    },
    showUserMore(item, message) {
      console.log(item, 'item')
      const name = item.map((item) => {
        return item.realName || item.realname
      })
      Dialog({ message: name.toString(), confirmButtonColor: '#1E8DF5' })
    },
    sliceArray(start, end, sliceArray, newArray = []) {
      newArray = sliceArray.slice(start, end)
      console.log(newArray)
      return newArray
    },
    //范围是否是全公司
    selectType(e) {
      // console.log(e,'范围是否是全公司')
      if (e.properties.actionerRules[0].select && e.properties.actionerRules[0].select[0] !== 'allStaff') {
        return true
      }
      return false
    },
    // 回显默认值数组
    getTargetArr(item, index) {
      if (item.approvalType === 'target_approval') {
        const { approvals } = item.properties.actionerRules[0]
        const list = this.getIdUser(approvals)
        return list
      }
      return item.operatorList
    },
    //是为默认显示的值
    getDefaultType(item) {
      return this.defaultType.includes(item.approvalType)
    },

    getName(arr) {
      let name = arr.map((item) => {
        return item.id
      })
      return name.toString()
    },
    //根据多个id匹配找用户信息列表
    getIdUserId(arr) {
      const list = this.allUserList.filter((item) => {
        return arr.includes(item.id)
      })
      return list.map((item) => {
        return {
          realname: item.realName,
          id: item.userId,
        }
      })
    },
    //根据多个id匹配找用户信息列表
    getIdUser(arr) {
      const list = this.allUserList.filter((item) => {
        return arr.includes(item.id)
      })
      return list.map((item) => {
        return {
          realname: item.realName,
          id: item.userId,
        }
      })
    },

    // 获取用户ID
    getUserIdList(array) {
      let list = []
      array.forEach((i) => {
        if (i.approvalType === 'target_select') {
          const approvals = i.properties.actionerRules ? i.properties.actionerRules[0].select[0] : ''
          if (approvals === 'approvals') {
            list = list.concat(i.properties.actionerRules[0].range.approvals)
          }
        }
        if (i.approvalType === 'target_approval') {
          list = list.concat(i.properties.actionerRules[0].approvals)
        }
      })
      return list
    },
    getNameList(arr) {
      if (arr.length > 0) {
        let name = arr.map((item, index) => {
          return item.realName || item.realname
        })
        // console.log(name, 'name')
        return name.toString()
      }
      return ''
    },
    getUserIdSelectlist(arr) {
      getSelectListByIds({ ids: arr.toString() }).then((res) => {
        this.allUserList = res.result
      })
    },
    getNodeName(item, index) {
      console.log(index, this.approvalsNodeList.length)
      const stepName = index === this.approvalsNodeList.length - 1 ? '(上一步)' : '(' + this.getNameList(item.operatorList) + ')'
      return item.nodeName + stepName
    },
    getPreviewProcessData() {
      getPreviewProcess({ formId: this.$route.query.id }).then((res) => {
        if (res.success) {
          this.showFlow = true
          

          this.processDataVoId = res.result.processCode
          this.processDataVo = res.result.nodeDtos
          let newpro = this.processDataVo.map((item) => {
            if (this.defaultType.includes(item.approvalType)) {
              item.selectUsers = item.operatorList
            }
          })
          this.getTaskId()
          this.steps = res.result.nodeDtos
          const list = [...res.result.nodeDtos]
          this.getUserIdSelectlist(this.getUserIdList(list))
          let approvalsNodeList = res.result.nodeDtos
            .map((item) => {
              if (item.nodeType === 'APPROVER' && item.nodeStauts === 'agree') {
                // 状态为同意的Id
                const isAgreeType = item.nodeStauts === 'agree' ? item.nodeId : ''
                // 拿到nodeID同意数组
                const state = res.result.nodeDtos.filter((item) => {
                  return item.nodeId === isAgreeType
                })
                // T同意的数组里面有没有进行中
                const runninSta = state.filter((item) => {
                  return item.nodeStauts === 'running'
                })
                if (runninSta.length == 0) {
                  return item
                }
              }
            })
            .filter((e) => {
              console.log(e, 'e', e == null)
              return e !== undefined
            })
          const result = approvalsNodeList.reduce((item, next) => {
            typeof item.find((ele) => ele['nodeId'] === next['nodeId']) === 'undefined' && item.push(next)
            return item
          }, [])
          this.approvalsNodeList = result
        } else {
          // Notify(res.message)
        }
      })
    },

    reject() {
      this.$router.push({ path: '/reject', query: this.$route.query })
    },
    agree() {
      this.$router.push({ path: '/agreement', query: this.$route.query })
    },

    onSubmit() {},
    // 自定义表单-通过id查询
    procFormInfoqueryByIds() {
      var id = this.$route.query.processInstanceId
      let par = {
        processInstanceId: id,
      }
      return queryFormData(par)
        .then((res) => {
          if (res.code !== 200) {
            this.$message.error(res.message)
            return
          }
          if (this.$route.query.processInstanceId) {
            this.queryProcessResultData()
          }
          this.procFormDatas = res.result
          const list = res.result.assemblyList.map((node) => {
            return {
              ...node,
              readonly: true,
            }
          })
          return list
        })
        .catch((e) => {
          this.formshow = false
        })
    },
    queryProcessResultData() {
      queryProcessResult({ processInstanceId: this.$route.query.processInstanceId }).then((res) => {
        if (res.code !== 200) {
          this.$message.error(res.message)
          return
        }
        let nodeDtosArr = res.result.nodeDtos.filter((item) => item.nodeType != "SERVICE")
        // console.log(res, 'dasd')approvedNodeNum
        this.stepsshow = true
        this.approvedNodeNum = res.result.approvedNodeNum
        this.processDataVoId = res.result.processCode
        this.processResult = res.result.processResult
        this.processDataVo = nodeDtosArr
        // this.getTaskId()
        this.steps = nodeDtosArr
        let approvalsNodeList = nodeDtosArr
          .map((item) => {
            if (item.nodeType === 'APPROVER' && item.nodeStauts === 'agree') {
              // 状态为同意的Id
              const isAgreeType = item.nodeStauts === 'agree' ? item.nodeId : ''
              // 拿到nodeID同意数组
              const state = nodeDtosArr.filter((item) => {
                return item.nodeId === isAgreeType
              })
              // T同意的数组里面有没有进行中
              const runninSta = state.filter((item) => {
                return item.nodeStauts === 'running'
              })
              if (runninSta.length == 0) {
                return item
              }
            }
          })
          .filter((e) => {
            console.log(e, 'e', e == null)
            return e !== undefined
          })
        const result = approvalsNodeList.reduce((item, next) => {
          typeof item.find((ele) => ele['nodeId'] === next['nodeId']) === 'undefined' && item.push(next)
          return item
        }, [])
        // console.log(result,'result')
        this.approvalsNodeList = result
      })
    },
  },
}
</script>
<style lang="less" scoped>
.footer {
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 60px;
  background: #ffffff;
  display: flex;
  align-items: center;
  justify-content: space-around;

  div {
    width: 60px;
    height: 30px;
    text-align: center;
    line-height: 30px;
    border-radius: 20px;
    border: 1px solid #999999;
    color: #999999;
  }

  .reject {
    border-color: #1e8df5;
    color: #1e8df5;
  }

  .agree {
    background-color: #1e8df5;
    border-color: #1e8df5;
    color: #ffffff;
  }
}
.confirmList {
  margin-top: 10px;
  margin-bottom: 20px;

  p {
    margin-top: 20px;
    text-align: center;
    font-size: 15px;
  }
}
.flow {
  padding-left: 15px;
  /* text-align: center; */
}
.stepIconFont {
  position: absolute;
  right: 30px;
  top: 10%;
}
.van-step--vertical {
  position: relative;
}
.body {
  height: 100vh;
  position: relative;
}
.title {
  .groupsDetail-letf {
    padding: 20px;
    background-color: #ffffff;
  }
  .groupsDetail-letf div {
    height: 20px;
    line-height: 20px;
  }
  .groupsDetail-letf div:nth-child(1) {
    font-size: 15px;
    margin-bottom: 10px;
    font-weight: 700;
  }

  .groupsDetail-letf div:nth-child(2),
  :nth-child(3) {
    color: #a6a6a6;
  }
}
</style>
<style>
.forms .layout-node {
  min-height: 100px !important;
}
.van-dialog__confirm, .van-dialog__confirm:active {
    color: #1989fa;
}
/* .van-step__icon--active, .van-step__icon--finish, .van-step__title--active, .van-step__title--finish {
    color: #1e8df5 !important;
} */
</style>